package Thread;


import java.util.concurrent.TimeUnit;

/**
 * Java中的锁机制一直是重点难点，那么我们本次对锁的介绍也会详细讲解。
 * 下面我们编写一个简单的多线程售票系统，系统中一共有10张票，用四个窗口去并行售票。
 * 关键字synchronized加到不同的地方含义不同，虽然都是加锁，但是加锁的对象不同。
 * 指定加锁对象：给指定对象加锁，进入同步代码之前要获取到该对象的锁。
 * 作用于实例方法：相当于对当前实例加锁 ，进入同步代码前要获取到该实例的锁
 * 作用于静态方法：相当于给当前类加锁，进入同步代码之前要获取当前类的锁。
 */

public class SynchronizedThread {
    public static void main(String[] args) {
        Ticket1 ticket1 = new Ticket1();
        Thread t1 = new Thread(ticket1, "一号窗口");
        Thread t2 = new Thread(ticket1, "二号窗口");
        Thread t3 = new Thread(ticket1, "三号窗口");
        Thread t4 = new Thread(ticket1, "四号窗口");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class Ticket implements Runnable {
    private int index = 0;
    private final static int MAX = 10;
    @Override
    public void run() {

        while (index < MAX) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            index++;
            System.out.println(Thread.currentThread().getId() + " 的号码是" +
                    index);
        }
    }
}

class Ticket1 implements Runnable{
    private int index = 0;
    private final  static int MAX = 10;
    private final Object lock = new Object();
    @Override
    public void run() {
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock) {
                if (index >= MAX) {
                    break;
                }
                index++;
                System.out.println(Thread.currentThread().getName() + " 的号  码是" + index);
            }
        }
    }
}
